<template>
  <div class="item-list">
    <vue-draggable-next v-model="group" handle=".move" animation="150" v-if="group && group.length > 0">
      <div class="item" v-for="(item, index) in group" :key="index">
        <i class="MC_iconfont MC_icon-tuodong-shu move" style="float: left; cursor: move"></i>
        <el-input
          class="content"
          v-model.trim="item.value"
          placeholder="请输入下拉框内容"
          :maxlength="50"
          show-word-limit
          :disabled="isSys"
          @change="itemChange($event, index)"
        ></el-input>
        <div class="operate">
          <el-radio v-model="isDefault" :label="item.key" style="margin-right: 0px" :disabled="isSys">默认</el-radio>
          <i v-if="!isSys" class="MC_iconfont MC_icon-shanchu2-xian" @click="remove(index)"></i>
        </div>
      </div>
    </vue-draggable-next>
    <div v-if="!isSys" @click="add" class="add-btn"><i class="MC_iconfont MC_icon-tianjia-xian" />添加选项</div>
  </div>
</template>
<script lang="ts">
/**
 * 单选：下拉单选 单选按钮
 * 设置数据 setData
 * 获取数据 getData
 */
import { defineComponent, watch, reactive, toRefs } from 'vue'
import { VueDraggableNext } from 'vue-draggable-next'
import { v4 as uuidv4 } from 'uuid'
import { ElMessage } from 'element-plus'
interface State {
  group: Record<string, unknown>[]
  isDefault: string
  isSys: boolean
}
export default defineComponent({
  name: 'SelectCom',
  components: { VueDraggableNext },
  props: {
    isSave: {
      type: Boolean,
      default: false
    }
  },
  emits: ['onItemChange'],
  setup(props, { emit }) {
    const STATE: State = reactive({
      group: [],
      isDefault: '', // 默认选中
      isSys: false
    })

    // 校验选项是否存在
    const itemChange = (val: any, idx: number) => {
      STATE.group.forEach((item, i) => {
        if (idx !== i && item.value === val) {
          setTimeout(() => {
            // 防止input框不失去焦点直接点保存 两个提示
            if (!props.isSave) {
              ElMessage.error('选项已存在')
            }
          }, 500)
          STATE.group[idx].value = ''
        }
      })
    }

    const remove = (index: number) => {
      if (STATE.group[index].key === STATE.isDefault) {
        STATE.isDefault = ''
      }
      STATE.group.splice(index, 1)
    }

    // 设置数据
    const setData = (data = [], isDefault: any = [], isSys: boolean) => {
      STATE.group = data
      STATE.isDefault = isDefault && isDefault.length ? isDefault[0].key : ''
      STATE.isSys = isSys
    }

    // 添加选项
    const add = () => {
      STATE.group.push({
        value: '',
        key: uuidv4().replace(/-/g, '')
      })
    }

    // 获取数据，筛选name为空的数据
    const getData = () => {
      const realGroup = STATE.group && STATE.group.filter((v) => v.value !== '')
      if (realGroup && realGroup.length) {
        realGroup.map((item: any) => {
          if (item.key === STATE.isDefault) {
            item.isDefault = true
          } else {
            item.isDefault = false
          }
        })
      }
      return realGroup
    }

    watch(
      [() => STATE.group, () => STATE.isDefault],
      () => {
        emit('onItemChange', getData())
      },
      { deep: true }
    )

    return {
      ...toRefs(STATE),
      remove,
      setData,
      add,
      getData,
      itemChange
    }
  }
})
</script>

<style lang="stylus" scoped>
.item-list
  width 100%
  border-radius 4px
  overflow hidden
  background var(--mc-gray1-color)
  padding 16px
  .MC_iconfont
    color rgba(0, 0, 0, 0.38)
  .item
    line-height 32px
    overflow hidden
    margin-bottom 16px
    .content
      width calc(100% - 133px)
      float left
      overflow hidden
      text-overflow ellipsis
      white-space nowrap
      margin-left 16px
    .operate
      float right
      line-height 32px
      :deep(.el-radio__inner)
        border-color rgba(0, 0, 0, 0.38)
      :deep(.el-radio__input.is-checked .el-radio__inner)
        border-color var(--mc-main-color)
      i
        color rgba(0, 0, 0, 0.38)
        margin-left 16px
        font-size 16px
        cursor pointer
        &:hover
          color #fc6c5c
  .add-btn
    cursor pointer
    color var(--mc-main-color)
    margin-left 10px
    .MC_icon-tianjia-xian
      margin-right 6px
      color var(--mc-main-color)
</style>
